<template>
	<view class="page" :style="{'--color':vuex_config.themeColor1}">
		<template v-if="dataForm.pk_id?true:false">

			<view class="card_main">
				<view class="card_top">
					<view class="title">{{cardForm.name}}</view>
					<view class="price">￥{{dataForm.market_price || 0}}</view>
					<view class="time">
						{{cardForm.start_date | formatTime}}<text style="margin: 0 6rpx;">~</text>{{cardForm.end_date | formatTime}}
					</view>
				</view>
				<view class="cell_box">
					<view class="cell_item" v-for="(item,index) in product_stock" :key="index">
						<view @click="select(index)" class="title u-line-1">{{item.name}}</view>
						<view class="num_box">
							<u-number-box :min="1" v-model="item.buyNum" input-height="54" input-width="104" :max="3">
							</u-number-box>
						</view>
						<view @click="select(index)"
							:class="['radio_view','iconfont',getStatus(indexList,index)?'iconfont-e721':'iconfont-e720']">
						</view>
					</view>
				</view>
			</view>

			<view class="user_box">
				<view class="user_item">
					<view class="title">*姓名</view>
					<input class="input_view" v-model="setForm.real_name" type="text" placeholder="请输入姓名" />
				</view>
				<view class="user_item">
					<view class="title">*联系电话</view>
					<input class="input_view" v-model="setForm.mobile" type="number" placeholder="请输入联系电话" />
				</view>
			</view>
			<button :class="['share_btn','u-reset-button',cardForm.num <= cardForm.record_num?'disabled':'act']"
				@click="getProd()">
				{{cardForm.num <= cardForm.record_num?'已派完':'立即领取'}}
			</button>

			<view class="shop_box">
				<view class="cont">
					<view class="shop_name">{{vuex_business.name}}</view>
					<view class="shop_address">{{vuex_business.address}}</view>
				</view>
				<view class="sign_box">
					<view @click="seeMap" class="address iconfont iconfont-e769"></view>
					<view @click="cell" class="phone iconfont iconfont-e68e"></view>
				</view>
			</view>
			<view class="parse_view" v-if="dataForm.details?true:false">
				<u-parse :html="dataForm.details"></u-parse>
			</view>

		</template>
		<sww-login></sww-login>
	</view>
</template>

<script>
	import {
		pageShare
	} from '@/mixins/pageShare.js';
	import {
		formatDate,
		isAfter,
		isBefore
	} from '@/utils/moment/index.js';
	import {
		uniCall
	} from '@/utils/uniPromise.js'
	import {
		payOrder
	} from '@/mixins/payOrder';
	import {
		isMobile
	} from '@/utils/validate.js'
	export default {
		mixins: [pageShare, payOrder],
		data() {
			return {
				cardId: null,
				prodId: null,
				orderNum: 0, // 已经下单数量
				indexList: [],
				current: 0,
				dataForm: {},
				product_stock: [],
				setForm: {
					real_name: '',
					mobile: ''
				},
				cardForm: {}
			}
		},
		filters: {
			formatTime(val) {
				return formatDate(new Date(val), 'YYYY-MM-DD HH:mm:ss');
			}
		},
		computed: {
			getStatus(list, id) {
				return (list, id) => {
					return list.some((item) => {
						return item === id
					})
				}
			}
		},
		onLoad(options) {
			if (options.cardId) {
				this.cardId = Number(options.cardId)
				// this.getUsedNum()
				this.$login('$initPage', null, '$initPage').then(() => {
					this.$initPage()
				})
			}
		},
		// 微信小程序分享(好友)
		onShareAppMessage: function() {
			return this.getShareAppMessage();
		},
		methods: {
			// 查询已下的订单数
			// getUsedNum() {
			// 	this.$GetQueryDataList('b_order', 1, 1, {
			// 		fk_business_id: this.vuex_business.pk_id,
			// 		remark: `礼宾卡:${this.prodId};派发人:${this.users_id}`
			// 	}).then((res) => {
			// 		this.orderNum = res.pageCount || 0
			// 	})
			// },
			$initPage() {
				this.getCardDetail()

				if (this.$isLogin()) {
					this.setForm = {
						...this.setForm,
						mobile: this.vuex_user.mobile,
						real_name: this.vuex_user.real_name
					}
				}
			},
			// 判断能否下单(是否新用户)
			getUseTime() {
				return new Promise((resolve, reject) => {
					if (this.cardForm.mode == 2) {
						let str1 = new Date().toDateString()
						let str2 = new Date(this.vuex_user.date_creation).toDateString()
						if (str1 == str2) {
							resolve()
						} else {
							uni.showModal({
								content: '当前服务只限新用户可领取',
								showCancel: false
							})
							reject()
						}
					} else {
						resolve()
					}
				})
			},
			select(index) {
				let newIndex = this.indexList.findIndex((id) => {
					return id === index
				})
				if (newIndex > -1) {
					this.indexList.splice(newIndex, 1)
				} else {
					if (this.indexList.length < 2) {
						this.indexList.push(index)
						// this.product_stock[index].buyNum = (this.product_stock[index].buyNum || 1)
					} else {
						this.$toast('最多只能选两个规格')
					}
				}
			},
			//  获取卡片信息
			getCardDetail() {
				this.$loading()
				this.$resPost('GetUsersCardInfo', {
					pk_id: this.cardId
				}).then(({
					data
				}) => {
					this.cardForm = {
						...data
					}
					if (this.$isLogin()) {
						this.getUseTime()
					}
					if (!this.dataForm.pk_id) {
						this.prodForm()
					} else {
						this.$hide()
					}
				})
			},
			prodForm() {
				this.$resPost('GetProductDetailed', {
					pk_id: this.cardForm.fk_pro_id
				}).then(({
					data
				}) => {
					this.product_stock = (data.product_stock || []).map((item) => {
						return {
							...item,
							buyNum: 0
						}
					})
					this.dataForm = {
						...data,
						product_stock: null
					}
					this.$hide()
				})
			},
			seeMap() {
				if (this.vuex_business.coordinate) {
					let arr = this.vuex_business.coordinate.split(',')
					let $this = this;
					let obj = {
						// #ifdef MP-ALIPAY
						name: this.vuex_business.address,
						address: this.vuex_business.address
						// #endif
					};
					uni.openLocation({
						latitude: Number(arr[0]),
						longitude: Number(arr[1]),
						...obj
					});
				} else {
					this.$toast('商家未开通导航')
				}
			},
			cell() {
				uniCall(this.vuex_business.custom_tel)
			},
			getProd() {
				if (this.cardForm.num <= this.cardForm.record_num) {
					return
				}
				this.$login('$initPage').then(() => {
					this.getUseTime().then(() => {
						if (!this.indexList[0] && this.indexList[0] !== 0) {
							this.$toast('请至少选择一个项目')
							return
						}
						let currentDate = new Date()
						if (isBefore(currentDate, this.cardForm.start_date)) {
							this.$toast('活动未开始')
							return
						} else if (isAfter(currentDate, this.cardForm.end_date)) {
							this.$toast('活动已结束')
							return
						}

						if (!this.setForm.mobile || !this.setForm.real_name) {
							this.$toast('请填写用户信息')
							return
						} else if (!isMobile(this.setForm.mobile)) {
							this.$toast('请填写正确的手机号')
							return
						}
						this.$u.debounce(
							() => {
								let json = []
								let totalPrice = 0
								let totalNum = 0
								let bol = true // 是否都设置了数量
								this.indexList.forEach((index, i) => {
									totalNum += this.product_stock[index].buyNum
									totalPrice += this.product_stock[index].amount
									if (this.product_stock[index].buyNum <= 0) {
										bol = false
									}
									json.push({
										fk_pro_id: this.dataForm.pk_id,
										fk_stock_id: this.product_stock[index].pk_id,
										num: this.product_stock[index].buyNum,
										name: this.product_stock[index].name,
										price: this.product_stock[index].amount
									})

								})
								if (!bol) {
									this.$toast('每项服务选择次数不能为0')
									return
								} else if (totalNum > 3) {
									this.$toast('项目体验总次数不能超过3次')
									return
								}
								this.saveUser()
								let params = {
									remark: `礼宾卡:${this.prodId};派发人:${this.cardForm.fk_users_id}`,
									type: 1, // 是否清理用户购物车 1-不清理 2-清理
									postage: 0, // 邮费
									total_amount: totalPrice, // 订单总金额
									coupon_id: '0',
									coupon: '0',
									name: this.setForm.real_name,
									mobile: this.setForm.mobile,
									json_detailed: JSON.stringify(json)
								};
								this._submitOrder(params, {
										totalPrice: 0,
										pay_type: 3,
										order_type: 1,
										tipName:'预约服务',
										tipContent:'是否立即领取'
									})
									.then(() => {})
									.catch(() => {});
							},
							1000,
							true
						);
					})
				})
			},
			// 创建订单
			// goCreate(params) {
			// 	let opts = {

			// 		updateApi: '',
			// 		redirectUrl: ''
			// 	}
			// 	this.createOrder({
			// 		...params
			// 	}, opts).then((data) => {
			// 		this.addRecord(data.order_no)
			// 		this.$resPost('UpdateOrderStatus', {
			// 			order_no: data.order_no,
			// 			type: opts.pay_type,
			// 		}, {}, {
			// 			timeout: '请求超时，请联系客服'
			// 		}).then(() => {
			// 			this.$linkTo('/package/order/list/index', 'redirectTo')
			// 		})
			// 	}).catch((orderId) => {
			// 		if (orderId) {
			// 			this.deleOrder(orderId)
			// 		}
			// 		// 下单失败、支付失败
			// 	})
			// },
			// 取消订单
			// deleOrder(orderId) {
			// 	this.$loading()
			// 	this.$resPost('DeleteOrderInfo', {
			// 			pk_id: orderId
			// 		})
			// 		.then(() => {
			// 			this.$linkTo('/package/order/list/index', 'redirectTo')
			// 			this.$hide();
			// 		})
			// 		.catch(() => {});
			// },
			// 添加记录
			onOrderUptateSuccess(data) {
				this.$resPost('AddUsersCardRecord', {
					info_id: this.cardId,
					remarks: `订单号：${data.order_no}`
				})
			},
			saveUser() {
				let params = {
					users_id: this.vuex_user.fk_users_id || '',
					users_webchat_id: this.vuex_user.pk_id || '',
					type: this.vuex_user.type > 0 ? this.vuex_user.type : 1,
					...this.setForm
				}
				this.$resPost('SetApplyDistributor', params)
			}
		},
	}
</script>
<style>
	page {
		background-color: #F5F5F5;
	}
</style>
<style lang="scss" scoped>
	.page {
		padding: 20rpx 20rpx 0;
	}

	.card_main {
		border: 4rpx solid #4BA6EE;
		display: flex;
		flex-direction: column;
		border-radius: 20rpx;
		overflow: hidden;
		min-height: 500rpx;

		.card_top {
			background-color: #4BA6EE;
			padding: 22rpx 16rpx 24rpx;
			flex: 1;
			overflow: hidden;
			color: #fff;
			min-height: 232rpx;
			text-align: center;
			display: flex;
			flex-direction: column;

			.title {
				font-size: 34rpx;
				margin-bottom: 22rpx;
			}

			.time {
				margin-top: auto;
				text-align: right;
			}
		}

		.cell_box {
			background-color: #fff;
			padding: 0 0 30rpx 26rpx;

			.cell_item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-bottom: 2rpx solid #F0F0F0;

				.title {
					flex: 1;
					overflow: hidden;
					font-weight: bold;
					line-height: 80rpx;
				}

				.radio_view {
					margin-left: 10rpx;
					padding: 0 20rpx;
					font-size: 36rpx;

					&.iconfont-e721 {
						color: var(--color);
					}
				}
			}
		}
	}

	.share_btn {
		background-color: #F5C344;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		font-size: 34rpx;
		margin: 30rpx 30rpx 20rpx;
		border-radius: 10rpx;

		&.disabled {
			background-color: #ddd;
		}

		&.act:active {
			opacity: .8;
		}
	}

	.shop_box {
		display: flex;
		background-color: #fff;
		padding: 28rpx;
		border-top: 2rpx solid #F0F0F0;
		border-bottom: 2rpx solid #F0F0F0;

		.cont {
			flex: 1;
			overflow: hidden;

			.shop_name {
				font-weight: bold;
			}

			.shop_address {
				color: #888888;
				font-size: 24rpx;
				margin-top: 10rpx;
			}
		}

		.sign_box {
			display: flex;
			align-items: center;

			.iconfont {
				font-size: 40rpx;
				padding: 0 14rpx;
				color: #4792EB;

				&.phone {
					color: #2C877A;
				}
			}
		}
	}

	.parse_view {
		background-color: #fff;
		margin-top: 24rpx;
		padding: 20rpx 14rpx;
	}

	.user_box {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;
		overflow: hidden;
		margin-top: 20rpx;

		.user_item {
			display: flex;
			align-items: center;
			border-bottom: 2rpx solid #ddd;

			&:last-of-type {
				border: none;
			}

			.input_view {
				flex: 1;
				overflow: hidden;
				text-align: right;
				line-height: 70rpx;
				height: 70rpx;
				min-height: 70rpx;
			}
		}
	}
</style>
